
package org.drip.service.product;

/*
 * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 */

/*!
 * Copyright (C) 2016 Lakshmi Krishnamurthy
 * 
 *  This file is part of DRIP, a free-software/open-source library for fixed income analysts and developers -
 * 		http://www.credit-trader.org/Begin.html
 * 
 *  DRIP is a free, full featured, fixed income rates, credit, and FX analytics library with a focus towards
 *  	pricing/valuation, risk, and market making.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *   	you may not use this file except in compliance with the License.
 *   
 *  You may obtain a copy of the License at
 *  	http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  	distributed under the License is distributed on an "AS IS" BASIS,
 *  	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  
 *  See the License for the specific language governing permissions and
 *  	limitations under the License.
 */

/**
 * FixFloatAPI contains the Functionality associated with the Horizon Analysis of the Fix Float Swap.
 * 
 * @author Lakshmi Krishnamurthy
 */

public class FixFloatAPI {

	static class ParFFC {
		double _dblFairPremium = java.lang.Double.NaN;;
		org.drip.product.rates.FixFloatComponent _ffc = null;

		ParFFC (
			final org.drip.product.rates.FixFloatComponent ffc,
			final double dblFairPremium)
		{
			_ffc = ffc;
			_dblFairPremium = dblFairPremium;
		}

		double fairPremium()
		{
			return _dblFairPremium;
		}

		org.drip.product.rates.FixFloatComponent ffc()
		{
			return _ffc;
		}
	};

	private static final ParFFC HorizonFixFloat (
		final org.drip.state.discount.DiscountCurve dc,
		final java.lang.String strMaturityTenor)
	{
		java.lang.String strCurrency = dc.currency();

		org.drip.analytics.date.JulianDate dt = dc.epoch();

		org.drip.market.otc.FixedFloatSwapConvention ffsc =
			org.drip.market.otc.IBORFixedFloatContainer.ConventionFromJurisdiction (strCurrency, "ALL",
				strMaturityTenor, "MAIN");

		if (null == ffsc) return null;

		org.drip.analytics.date.JulianDate dtEffective = dt.subtractBusDays (ffsc.spotLag(),
			ffsc.fixedStreamConvention().calendar());

		org.drip.product.rates.FixFloatComponent ffc = ffsc.createFixFloatComponent (dtEffective,
			strMaturityTenor, 0., 0., 1.);

		if (null == ffc) return null;

		org.drip.param.market.CurveSurfaceQuoteContainer csqc = new
			org.drip.param.market.CurveSurfaceQuoteContainer();

		if (!csqc.setFundingState ((org.drip.state.discount.MergedDiscountForwardCurve) dc)) return null;

		try {
			double dblFairPremium = ffc.measureValue (org.drip.param.valuation.ValuationParams.Spot
				(dt.julian()), null, csqc, null, "FairPremium");

			return new ParFFC (ffsc.createFixFloatComponent (dtEffective, strMaturityTenor, dblFairPremium,
				0., 1.), dblFairPremium);
		} catch (java.lang.Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	private static final org.drip.param.market.CurveSurfaceQuoteContainer FixingCSQS (
		final org.drip.product.rates.Stream floatingStream,
		final int iDate,
		final org.drip.state.discount.DiscountCurve dc)
	{
		org.drip.analytics.cashflow.CompositePeriod cpFixing = floatingStream.containingPeriod (iDate);

		if (null == cpFixing) return null;

		org.drip.analytics.cashflow.ComposableUnitPeriod cupEnclosing = cpFixing.enclosingCUP (iDate);

		if (null == cupEnclosing || !(cupEnclosing instanceof
			org.drip.analytics.cashflow.ComposableUnitFloatingPeriod))
			return null;

		org.drip.param.market.CurveSurfaceQuoteContainer csqc = new
			org.drip.param.market.CurveSurfaceQuoteContainer();

		if (!csqc.setFundingState ((org.drip.state.discount.MergedDiscountForwardCurve) dc)) return null;

		try {
			return csqc.setFixing (((org.drip.analytics.cashflow.ComposableUnitFloatingPeriod)
				cupEnclosing).referenceIndexPeriod().fixingDate(), floatingStream.forwardLabel(),
					cupEnclosing.baseRate (csqc)) ? csqc : null;
		} catch (java.lang.Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	private static final org.drip.historical.attribution.FixFloatMarketSnap MarketValuationSnap (
		final org.drip.product.rates.FixFloatComponent ffc,
		final org.drip.state.discount.DiscountCurve dc,
		final org.drip.param.market.CurveSurfaceQuoteContainer csqc,
		final double dblRollDownFairPremium)
	{
		if (!csqc.setFundingState ((org.drip.state.discount.MergedDiscountForwardCurve) dc)) return null;

		org.drip.analytics.date.JulianDate dt = dc.epoch();

		java.util.Map<java.lang.String, java.lang.Double> mapFixFloat = ffc.value
			(org.drip.param.valuation.ValuationParams.Spot (dt.julian()), null, csqc, null);

		if (null == mapFixFloat || !mapFixFloat.containsKey ("Accrued") || !mapFixFloat.containsKey
			("CleanFixedDV01") || !mapFixFloat.containsKey ("CleanPV") || !mapFixFloat.containsKey
				("FairPremium"))
			return null;

		double dblCleanPV = mapFixFloat.get ("CleanPV");

		double dblFairPremium = mapFixFloat.get ("FairPremium");

		double dblFairPremiumSensitivity = 10000. * mapFixFloat.get ("CleanFixedDV01");

		try {
			org.drip.historical.attribution.FixFloatMarketSnap ffpms = new
				org.drip.historical.attribution.FixFloatMarketSnap (dt, dblCleanPV);

			return ffpms.setMaturityDate (ffc.maturityDate()) && ffpms.setResetDate (new
				org.drip.analytics.date.JulianDate ((int) (double) mapFixFloat.get ("ResetDate"))) &&
					ffpms.setResetRate (mapFixFloat.get ("ResetRate")) && ffpms.setCleanFixedDV01
						(dblFairPremiumSensitivity) && ffpms.setCurrentFairPremium (dblFairPremium) &&
							ffpms.setRollDownFairPremium (dblRollDownFairPremium) && ffpms.setAccrued
								(mapFixFloat.get ("Accrued")) && ffpms.setFloaterLabel
									(ffc.derivedStream().forwardLabel().fullyQualifiedName()) &&
										ffpms.setSwapRateMarketFactor (dblFairPremium, -1. *
											dblFairPremiumSensitivity, dblFairPremium) ? ffpms : null;
		} catch (java.lang.Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	private static final double RollDownFairPremium (
		final org.drip.product.rates.FixFloatComponent ffc,
		final int iSpotDate,
		final org.drip.state.discount.DiscountCurve dcPrevious,
		final org.drip.param.market.CurveSurfaceQuoteContainer csqc)
		throws java.lang.Exception
	{
		if (!csqc.setFundingState ((org.drip.state.discount.MergedDiscountForwardCurve) dcPrevious))
			throw new java.lang.Exception ("FixFloatAPI::RollDownFairPremium => Invalid Inputs");

		java.util.Map<java.lang.String, java.lang.Double> mapFixFloat = ffc.value
			(org.drip.param.valuation.ValuationParams.Spot (iSpotDate), null, csqc, null);

		if (null == mapFixFloat || !mapFixFloat.containsKey ("FairPremium"))
			throw new java.lang.Exception ("FixFloatAPI::RollDownFairPremium => Invalid Inputs");

		return mapFixFloat.get ("FairPremium");
	}

	/**
	 * Compute the Horizon Change Attribution Details for the Specified Fix-Float Swap
	 * 
	 * @param dcFirst First Day Discount Curve
	 * @param dcSecond Second Date Discount Curve
	 * @param strMaturityTenor Fix Float Swap Maturity Tenor
	 * 
	 * @return The Horizon Change Attribution Instance
	 */

	public static final org.drip.historical.attribution.PositionChangeComponents HorizonChangeAttribution (
		final org.drip.state.discount.DiscountCurve dcFirst,
		final org.drip.state.discount.DiscountCurve dcSecond,
		final java.lang.String strMaturityTenor)
	{
		if (null == dcFirst || null == dcSecond) return null;

		int iFirstDate = dcFirst.epoch().julian();

		int iSecondDate = dcSecond.epoch().julian();

		java.lang.String strCurrency = dcSecond.currency();

		if (!strCurrency.equalsIgnoreCase (dcFirst.currency()) || iFirstDate >= iSecondDate) return null;

		ParFFC parFFC = HorizonFixFloat (dcFirst, strMaturityTenor);

		if (null == parFFC) return null;

		org.drip.product.rates.FixFloatComponent ffc = parFFC.ffc();

		if (null == ffc) return null;

		double dblInitialFairPremium = parFFC.fairPremium();

		org.drip.param.market.CurveSurfaceQuoteContainer csqc = FixingCSQS (ffc.derivedStream(), iSecondDate,
			dcFirst);

		if (null == csqc) return null;

		double dblRollDownFairPremium = java.lang.Double.NaN;

		try {
			dblRollDownFairPremium = RollDownFairPremium (ffc, iSecondDate, dcFirst, csqc);
		} catch (java.lang.Exception e) {
			e.printStackTrace();

			return null;
		}

		if (!org.drip.quant.common.NumberUtil.IsValid (dblRollDownFairPremium)) return null;

		org.drip.historical.attribution.FixFloatMarketSnap ffpmsFirst = MarketValuationSnap (ffc, dcFirst,
			csqc, dblRollDownFairPremium);

		if (null == ffpmsFirst || !ffpmsFirst.setInitialFairPremium (dblInitialFairPremium) ||
			!ffpmsFirst.setFixedCoupon (dblInitialFairPremium))
			return null;

		org.drip.historical.attribution.FixFloatMarketSnap ffpmsSecond = MarketValuationSnap (ffc, dcSecond,
			csqc, dblRollDownFairPremium);

		if (null == ffpmsSecond || !ffpmsSecond.setInitialFairPremium (dblInitialFairPremium) ||
			!ffpmsSecond.setFixedCoupon (dblInitialFairPremium))
			return null;

		try {
			return new org.drip.historical.attribution.PositionChangeComponents (false, ffpmsFirst,
				ffpmsSecond, 0.);
		} catch (java.lang.Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * Generate the Funding Curve Horizon Metrics
	 * 
	 * @param adtSpot Array of Spot
	 * @param iHorizonGap The Horizon Gap
	 * @param astrFixFloatMaturityTenor Array of Fix Float Maturity Tenors
	 * @param aadblFixFloatQuote Array of Fix Float Swap Rates
	 * @param strCurrency Funding Currency
	 * @param strMaturityTenor Maturity Tenor
	 * @param iLatentStateType Latent State Type
	 * 
	 * @return The Funding Curve Horizon Metrics
	 */

	public static final java.util.List<org.drip.historical.attribution.PositionChangeComponents>
		HorizonChangeAttribution (
			final org.drip.analytics.date.JulianDate[] adtSpot,
			final int iHorizonGap,
			final java.lang.String[] astrFixFloatMaturityTenor,
			final double[][] aadblFixFloatQuote,
			final java.lang.String strCurrency,
			final java.lang.String strMaturityTenor,
			final int iLatentStateType)
	{
		if (null == adtSpot || 0 >= iHorizonGap || null == astrFixFloatMaturityTenor || null ==
			aadblFixFloatQuote)
			return null;

		int iNumClose = adtSpot.length;
		int iNumCalibrationInstrument = astrFixFloatMaturityTenor.length;

		java.util.List<org.drip.historical.attribution.PositionChangeComponents> lsPCC = new
			java.util.ArrayList<org.drip.historical.attribution.PositionChangeComponents>();

		for (int i = iHorizonGap; i < iNumClose; ++i) {
			int iNumSecondQuote = null == aadblFixFloatQuote[i] ? 0 : aadblFixFloatQuote[i].length;
			int iNumFirstQuote = null == aadblFixFloatQuote[i - iHorizonGap] ? 0 :
				aadblFixFloatQuote[i - iHorizonGap].length;

			if (0 == iNumFirstQuote || iNumFirstQuote != iNumCalibrationInstrument || 0 ==
				iNumSecondQuote || iNumSecondQuote != iNumCalibrationInstrument)
				continue;

			org.drip.state.discount.MergedDiscountForwardCurve dcFirst =
				org.drip.service.template.LatentMarketStateBuilder.FundingCurve (adtSpot[i - iHorizonGap],
					strCurrency, null, null, "ForwardRate", null, "ForwardRate", astrFixFloatMaturityTenor,
						aadblFixFloatQuote[i - iHorizonGap], "SwapRate", iLatentStateType);

			org.drip.state.discount.MergedDiscountForwardCurve dcSecond =
				org.drip.service.template.LatentMarketStateBuilder.FundingCurve (adtSpot[i], strCurrency,
					null, null, "ForwardRate", null, "ForwardRate", astrFixFloatMaturityTenor,
						aadblFixFloatQuote[i], "SwapRate", iLatentStateType);

			lsPCC.add (HorizonChangeAttribution (dcFirst, dcSecond, strMaturityTenor));
		}

		return lsPCC;
	}
}
